//
// ProducterStream.cpp for  in /home/herpec_j/Projets/
//
// Made by Jonathan
// Login   <herpec_j@epitech.net>
//
// Started on  Tue Sep 10 09:08:52 2013 Jonathan
// Last update Fri Sep 20 18:33:29 2013 Jonathan
//

#include		<stdexcept>
#include		<cstdlib>
#include		<sys/stat.h>
#include		<fcntl.h>
#include		<unistd.h>

#include		"Parsing/ProducterStream.hpp"

namespace		Parsing
{
  ProducterStream::ProducterStream(void)
  {
    mFd = -1;
    mEOF = true;
  }

  std::string		ProducterStream::NextString(void)
  {
    char		buffer[4096] = {'\0'};
    unsigned int	position = 0;

    if (mFd == -1)
      {
	throw std::runtime_error("Stream not initialized");
      }
    while (position < 4096 - 1)
      {
	ssize_t		return_value = read(mFd, buffer + position, 1);

	if (return_value == -1)
	  {
	    throw std::runtime_error("Impossible to read");
	  }
	else if (return_value == 0)
	  {
	    if (mEOF == false)
	      {
		mEOF = true;
		return (std::string(buffer));
	      }
	    else
	      {
		throw std::runtime_error("End of file");
	      }
	  }
	else
	  {
	    ++position;
	  }
      }
    return (std::string(buffer));
  }

  bool			ProducterStream::LoadFile(char *path)
  {
    if (path == NULL || (mFd != -1 && mFd != STDIN_FILENO && close(mFd) == -1))
      {
	mEOF = true;
	return (false);
      }
    if ((mFd = open(path, O_RDONLY)) == -1)
      {
	mEOF = true;
	return (false);
      }
    mEOF = false;
    return (true);
  }

  bool			ProducterStream::LoadStdin(void)
  {
    if (mFd != -1 && mFd != STDIN_FILENO && close(mFd) == -1)
      {
	mEOF = true;
	return (false);
      }
    mFd = STDIN_FILENO;
    mEOF = false;
    return (true);
  }

  ProducterStream::~ProducterStream(void)
  {
    return;
  }
};
